package com.techwells.taco.utils;

import java.util.Timer;
import java.util.TimerTask;

import android.graphics.Color;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

/**
 * 验证码
 */
public class VcodeUitl {

	private static VcodeUitl vCodeUitl;
	private TextView view;

	private Timer timer;
	private static final int TIME_COUNT_DOWN = 1;
	private int timeCount;
	private static final int TIMER_COUNT_DOWN = 60;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TIME_COUNT_DOWN:
				if (timeCount > 0) {
					view.setEnabled(false);
					String string = timeCount + "s后再次发送";
					SpannableString builder = new SpannableString(string);
					builder.setSpan(new ForegroundColorSpan(Color.RED), 0, string.length()-5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); 
					view.setText(builder);
				} else {
					view.setText("获取验证码");
					view.setEnabled(true);
					timer.cancel();
				}
				break;

			default:
				break;
			}
		};
	};

	public static VcodeUitl instance() {
		synchronized (VcodeUitl.class) {
			if (null == vCodeUitl) {
				vCodeUitl = new VcodeUitl();
			}
		}
		return vCodeUitl;
	}

	public void setViewToVcode(TextView view) {
		this.view = view;
		startTimeCount();
	}

	public void startTimeCount() {
		timer = new Timer();
		timeCount = TIMER_COUNT_DOWN;
		timer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				timeCount -= 1;
				handler.sendMessage(handler.obtainMessage(TIME_COUNT_DOWN));
			}
		}, 0, 1000);
	}

	public void stopTimeCount(/* int viewId */) {
		// if(view.getId() == viewId){
		view.setText("获取验证码");
		view.setEnabled(true);
		timer.cancel();
		// }
	}

}
